package com.sleepfish.activiti.framework.core.script.impl;


import com.sleepfish.activiti.framework.core.script.BpmTaskAssignScript;
import com.sleepfish.activiti.util.SetUtils;
import com.sleepfish.common.core.domain.entity.SysDept;
import com.sleepfish.common.core.domain.entity.SysUser;
import com.sleepfish.system.service.ISysDeptService;
import com.sleepfish.system.service.ISysUserService;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Set;

import static java.util.Collections.emptySet;

/**
 * 分配给发起人的 Leader 审批的 Script 实现类
 * 目前 Leader 的定义是，
 *
 * @author xiaochao
 */
public abstract class BpmTaskAssignLeaderAbstractScript implements BpmTaskAssignScript {

    @Resource
    private ISysUserService adminUserApi;
    @Resource
    private ISysDeptService deptApi;

    protected Set<Long> calculateTaskCandidateUsers(TaskEntity task, int level) {
        Assert.isTrue(level > 0, "level 必须大于 0");
        // 获得发起人
        Long startUserId = Long.parseLong(task.getProcessInstance().getStartUserId());
        // 获得对应 leve 的部门
        SysDept dept = null;
        for (int i = 0; i < level; i++) {
            // 获得 level 对应的部门
            if (dept == null) {
                dept = getStartUserDept(startUserId);
                if (dept == null) { // 找不到发起人的部门，所以无法使用该规则
                    return emptySet();
                }
            } else {
                SysDept parentDept = deptApi.selectDeptById(dept.getParentId());
                if (parentDept == null) { // 找不到父级部门，所以只好结束寻找。原因是：例如说，级别比较高的人，所在部门层级比较少
                    break;
                }
                dept = parentDept;
            }
        }
        SysUser sysUser = adminUserApi.selectUserByUserName(dept.getLeader());


        return dept.getLeader() != null ? SetUtils.asSet(sysUser.getUserId()) : emptySet();
    }

    private SysDept getStartUserDept(Long startUserId) {
        SysUser startUser = adminUserApi.selectUserById(startUserId);
        if (startUser.getDeptId() == null) { // 找不到部门，所以无法使用该规则
            return null;
        }
        return deptApi.selectDeptById(startUser.getDeptId());
    }

}
